import React, { forwardRef, useEffect, useImperativeHandle } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const MAX_CHARS_PER_LINE = 80; // 每行最大字符数

const CustomReactQuill = forwardRef((props, ref) => {
  const quillRef = React.useRef(null);
  
  useImperativeHandle(ref, () => ({
    getEditor: () => quillRef.current?.getEditor(),
  }));

  useEffect(() => {
    const quill = quillRef.current?.getEditor();
    if (!quill) return;

    const handleTextChange = () => {
      const text = quill.getText();
      const lines = text.split('\n');
      
      let modified = false;
      const newLines = lines.map(line => {
        if (line.length > MAX_CHARS_PER_LINE) {
          modified = true;
          return line.substring(0, MAX_CHARS_PER_LINE) + '\n' + line.substring(MAX_CHARS_PER_LINE);
        }
        return line;
      });

      if (modified) {
        quill.setText(newLines.join('\n'));
      }
    };

    quill.on('text-change', handleTextChange);
    
    return () => {
      quill.off('text-change', handleTextChange);
    };
  }, []);

  return <ReactQuill ref={quillRef} {...props} />;
});

export default CustomReactQuill;
